// packageA/pages/partsOrderList/partsOrderList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //订单类型
    optionType: [],
    valueType: -1,
    //状态
    optionState: [{
        value: -1,
        text: "订单状态",
      },{
        value: 1,
        text: "已完成",
      },{
        value: 2,
        text: "待审批",
      },{
        value: 3,
        text: "已驳回",
      },{
        value: 4,
        text: "待发货",
      },{
        value: 5,
        text: "部分发出",
      },{
        value: 6,
        text: "全部发出，待收货",
      },{
        value: 7,
        text: "待入库",
      },{
        value: 8,
        text: "部分入库",
      }
    ],  
    valueState: -1,
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //开始时间
    startTime: '开始时间',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束时间',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
    },
    //登录用户
    user:null,
    //驳回原因
    showReject:false,
    //驳回原因内容
    rejectValue:'',
    //驳回传参
    rejectParam:null,
    //用户权限
    authority:null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      user: app.globalData.userInfo,
      authority:app.globalData.authority
    })

    //订单类型字典
    this.getDictionary();

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      selectFields: ['id', 'cities', 'totalPurchasePrice', 'remark', 'server', 'staff', 'citiesName', 'freight','state', 'serverId', 'factoryName', 'address', 'purchasingTime', 'purchaseClassify', 'factoryId','operation', 'orderNo', 'contact', 'factory', 'reject', 'serverName', 'parts', 'logistics',
      'equipmentNo', 'salesperson', 'consignee', 'phone', 'clientDepart', 'shippedNum', 'appId', 'outStorageType','inStorageType', 'dataAuthority', 'totalSalePrice', 'project', 'orderPersonnel', 'purchaseParts','approvalProcess', 'currentApprovalMan', 'purchaseApproval'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    //搜索单号
    if(this.data.searchValue){
      dataObj.orderNo='%' +this.data.searchValue+ '%';
    }

    //订单类型
    if(this.data.valueType!=-1){
      dataObj['purchaseClassify.id']=this.data.valueType;
    }

    //订单状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
    }

    //下单时间
    if(this.data.startTime!='开始时间' && this.data.endTime!='结束时间'){
      dataObj.complex=[{
        and: {
          createDate: {
            ">=": this.data.startTime + " 00:00:00",
            "<=": this.data.endTime + " 23:59:59"
          }
        }
      }]  
    }

    let param = {
      isAuth: true,
      className: 'partsPurchaseOrder',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //下单时间
          if(item.purchasingTime){
            item.purchasingTime=util.timeFormat(item.purchasingTime);
          }
          
          //状态
          switch(item.state){
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-1';
              break;
            case 2:
              item.stateWord='待审批';
              item.stateClass='c-2';
              break;
            case 3:
              item.stateWord='已驳回';
              item.stateClass='c-3';
              break;
            case 4:
              item.stateWord='待发货';
              item.stateClass='c-4';
              break;
            case 5:
              item.stateWord='部分发出';
              item.stateClass='c-5';
              break;
            case 6:
              item.stateWord='全部发出，待收货';
              item.stateClass='c-6';
              break;
            case 7:
              item.stateWord='待入库';
              item.stateClass='c-7';
              break;
            case 8:
              item.stateWord='部分入库';
              item.stateClass='c-8';
              break;
          }
        });

        console.log('配件采购列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },  

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //订单类型
  onChangeType({detail}){
    this.setData({ 
      valueType: detail
    }) 
    this.refreshListAndPage();
  },

  //状态
  onChangeState({detail}){
    this.setData({ 
      valueState: detail
    }) 
    this.refreshListAndPage();
  },

  //查询字典-订单类型
  getDictionary(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'partsPurchaseClassify',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[{
          value:-1,
          text:'订单类型'
        }];
        result.forEach(item => {
          arr.push({
            value:item.id,
            text:item.name
          });
        });
        this.setData({
          optionType: arr
        })
      }
    }).catch((error) => {
    })
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      startTime:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();

    if(this.data.endTime!='结束时间'){
      this.refreshListAndPage();
    }  
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      endTime:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();

    if(this.data.startTime!='开始时间'){
      this.refreshListAndPage();
    }
  },

  //清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始时间',
      endTime: '结束时间'
    })
    
    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
  },

  //跳转添加/编辑
  goToAdd(e){
    let obj={};

    if(e.currentTarget.dataset.detail){
      let detail=e.currentTarget.dataset.detail;
      obj.id=detail.id;
    }

    wx.navigateTo({
      url: "/packageA/pages/partsOrderAdd/partsOrderAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转查看
  goToLook(e){
    let obj={
      id:e.currentTarget.dataset.detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/partsOrderDetail/partsOrderDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //作废
  onVoid(e){
    Dialog.confirm({
      title: '确认作废此采购单吗',
      confirmButtonText:'确认',
      cancelButtonText:'不作废了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;     
      let operation=detail.operation;
      operation.push({
        user: app.globalData.userInfo.userName,
        date: util.timeFormat(new Date()),
        log: "作废订单"        
      });

      let param={
        className:'partsPurchaseOrder',
        data:{
          id: detail.id,
          validState: 0,
          operation: operation
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已作废');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },
  
  //审批
  onApprove(e){
    let detail=e.currentTarget.dataset.detail;

    Dialog.confirm({
      title: '请审批',
      confirmButtonText:'通过',
      cancelButtonText:'驳回'
    }).then(() => {
      Dialog.confirm({
        title: '是否通过当前采购订单',
        confirmButtonText:'通过',
        cancelButtonText:'取消'
      }).then(() => {
        //通过
        this.pass(detail);
  
      }).catch(() => {
      });

    }).catch(() => {
      Dialog.confirm({
        title: '是否驳回当前采购计划',
        confirmButtonText:'驳回',
        cancelButtonText:'取消'
      }).then(() => {        
        this.setData({
          //显示驳回原因 
          showReject: true,
          //驳回的参数
          rejectParam:{
            id: detail.id,
            operation: detail.operation
          }
        })
  
      }).catch(() => {
      });
    });
  },

  //通过
  pass(detail){
    let operation=detail.operation;

    operation.push({
      user: app.globalData.userInfo.userName,
      date: util.timeFormat(new Date()),
      log: "配件采购审批通过"
    });

    let param={
      className:'partsPurchaseOrder',
      data:{
        id: detail.id,
        state: 4,
        operation: operation
      }
    } 

    CommonService.goSave(param).then(res=>{       
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('操作成功');
        setTimeout(() => {
          this.refreshListAndPage();
        }, 1000); 
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },  

  //获取驳回原因
  onGetReject(e){
    this.setData({
      rejectValue: e.detail.value,
    })
  },

  //隐藏驳回原因
  onCloseReject(){
    this.setData({ 
			showReject: false
		})
  },

  //确认驳回
  onReject(){
    let rejectValue=this.data.rejectValue;
    if(rejectValue && rejectValue.trim()){
      let obj=this.data.rejectParam;
      obj.operation.push({
        user: app.globalData.userInfo.userName,
        date: util.timeFormat(new Date()),
        log: '驳回,原因：' + rejectValue.trim()
      });
      obj.state=3;

      let param={
        className:'partsPurchaseOrder',
        data:obj
      }
      
      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          this.onCloseReject()
          Toast.success('操作成功');

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000); 
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
      
    }else{
      Toast.fail('请输入驳回原因');
    }  
  },

  //跳转发货
  goToSend(e){
    let detail=e.currentTarget.dataset.detail;

    //配件数量
    let parts=detail.parts;
    let num=0;
    parts.forEach(item => {
		  num+=item.num;
		});

    let obj={
      orderId: detail.id,
      state: detail.state,
      orderNo: detail.orderNo
    }

    wx.navigateTo({
      url: "/packageA/pages/partsSend/partsSend?paramObj="+JSON.stringify(obj)
    })
  },

  //确认收货
  onReceive(e){
    Dialog.confirm({
      title: '是否已验收货物？',
      confirmButtonText:'确认收货',
      cancelButtonText:'取消'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;     
      let operation=detail.operation;
      operation.push({
        user: app.globalData.userInfo.userName,
        date: util.timeFormat(new Date()),
        log: "确认收货"        
      });

      let param={
        className:'partsPurchaseOrder',
        data:{
          id: detail.id,
          state: 1,
          operation: operation
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('操作成功');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
      
    }).catch(() => {
    });
  },

  //完成
  onComplete(e){
    Dialog.confirm({
      title: '当前订单中含有未发货配件，',
      message:'是否确认关闭该订单',
      confirmButtonText:'确认',
      cancelButtonText:'取消'
    }).then(() => {

      let detail=e.currentTarget.dataset.detail;
      let user=this.data.user;

      let param={
        className:'partsPurchaseOrder',
        data:{
          id: detail.id,
          state: 1,
          completeUser: {
            id: user.id,
            name: user.username
          }
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('操作成功');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
      
    }).catch(() => {
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})